<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天功能测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        textarea {
            height: 100px;
            resize: vertical;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
        }
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .response-area {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #e9ecef;
        }
        .response-text {
            white-space: pre-wrap;
            line-height: 1.6;
        }
        .test-buttons {
            margin-top: 20px;
        }
        .test-btn {
            background: #28a745;
            margin-bottom: 10px;
        }
        .test-btn:hover {
            background: #218838;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 AI聊天功能测试</h1>
        
        <form id="chatForm">
            <div class="form-group">
                <label for="prompt">用户输入:</label>
                <textarea id="prompt" name="prompt" placeholder="请输入您的问题或消息" required>你好，请介绍一下你自己</textarea>
            </div>
            
            <div class="form-group">
                <label for="temperature">温度 (0.0-2.0):</label>
                <input type="range" id="temperature" name="temperature" min="0" max="20" value="7" step="1">
                <span id="temperatureValue">0.7</span>
            </div>
            
            <div class="form-group">
                <label for="maxTokens">最大长度:</label>
                <input type="number" id="maxTokens" value="2048" min="100" max="4096" class="form-control">
            </div>
            
            <div class="form-group">
                <label for="streamMode">流式模式:</label>
                <input type="checkbox" id="streamMode" class="form-control" style="width: auto;">
                <span style="font-size: 12px; color: #666;">启用流式回复，实时显示AI回复过程</span>
            </div>
            
            <button type="submit" id="submitBtn">💬 发送消息</button>
            <button type="button" onclick="clearResponse()">🗑️ 清空响应</button>
        </form>
        
        <div class="test-buttons">
            <h3>快速测试:</h3>
            <button class="test-btn" onclick="sendTestMessage('你好，请介绍一下你自己')">自我介绍测试</button><br>
            <button class="test-btn" onclick="sendTestMessage('帮我写一个Java Hello World程序')">编程测试</button><br>
            <button class="test-btn" onclick="sendTestMessage('解释一下什么是人工智能')">知识问答测试</button><br>
            <button class="test-btn" onclick="sendTestMessage('给我讲个笑话')">娱乐测试</button><br>
            <button class="test-btn" onclick="sendTestMessage('1+1等于几？')">数学测试</button>
        </div>
        
        <div id="status" class="status" style="display: none;"></div>
        
        <div id="responseArea" class="response-area">
            <h3>AI响应:</h3>
            <div id="response" class="response-text"></div>
            <div class="request-info">
                <strong>请求ID:</strong> <span id="requestId">-</span>
            </div>
        </div>
    </div>

    <script>
        // 温度滑块事件
        document.getElementById('temperature').addEventListener('input', function() {
            document.getElementById('temperatureValue').textContent = (this.value / 10).toFixed(1);
        });

        // 表单提交
        document.getElementById('chatForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const prompt = document.getElementById('prompt').value;
            const temperature = parseFloat(document.getElementById('temperature').value) / 10;
            const maxTokens = parseInt(document.getElementById('maxTokens').value);
            const streamMode = document.getElementById('streamMode').checked;
            
            if (!prompt.trim()) {
                alert('请输入消息内容');
                return;
            }
            
            // 显示加载状态
            const submitBtn = document.getElementById('submitBtn');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '发送中...';
            submitBtn.disabled = true;
            
            try {
                if (streamMode) {
                    // 流式模式
                    await sendStreamMessage(prompt, temperature, maxTokens);
                } else {
                    // 同步模式
                    await sendSyncMessage(prompt, temperature, maxTokens);
                }
            } catch (error) {
                console.error('请求失败:', error);
                document.getElementById('response').textContent = '网络错误: ' + error.message;
                document.getElementById('requestId').textContent = 'N/A';
            } finally {
                // 恢复按钮状态
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }
        });

        // 发送同步消息
        async function sendSyncMessage(prompt, temperature, maxTokens) {
            const requestData = {
                prompt: prompt,
                temperature: temperature,
                maxTokens: maxTokens,
                streamMode: false
            };
            
            console.log('发送同步聊天请求:', requestData);
            
            const response = await fetch('/api/ai/chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });
            
            const result = await response.json();
            console.log('收到AI响应:', result);
            
            if (result.success) {
                document.getElementById('response').textContent = result.response;
                document.getElementById('requestId').textContent = result.requestId || 'N/A';
            } else {
                document.getElementById('response').textContent = '错误: ' + result.errorMessage;
                document.getElementById('requestId').textContent = 'N/A';
            }
        }

        // 发送流式消息
        async function sendStreamMessage(prompt, temperature, maxTokens) {
            const requestData = {
                prompt: prompt,
                temperature: temperature,
                maxTokens: maxTokens,
                streamMode: true
            };
            
            console.log('发送流式聊天请求:', requestData);
            
            // 清空响应区域
            document.getElementById('response').textContent = '';
            document.getElementById('requestId').textContent = '流式响应中...';
            
            const response = await fetch('/api/ai/chat/stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let fullResponse = '';
            let buffer = '';
            
            try {
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) {
                        console.log('流式响应结束');
                        break;
                    }
                    
                    // 解码响应数据
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    
                    // 保留最后一行（可能不完整）
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (line.trim() === '') continue;
                        
                        if (line.startsWith('event: ')) {
                            const eventType = line.substring(7).trim();
                            console.log('收到事件类型:', eventType);
                        } else if (line.startsWith('data: ')) {
                            const data = line.substring(6).trim();
                            console.log('收到数据:', data);
                            
                            if (data && !data.includes('AI开始回复')) {
                                // 文本数据
                                fullResponse += data;
                                document.getElementById('response').textContent = fullResponse;
                            }
                        }
                    }
                }
                
                document.getElementById('requestId').textContent = '流式响应完成';
                
            } finally {
                reader.releaseLock();
            }
        }

        // 发送测试消息
        function sendTestMessage(text) {
            document.getElementById('prompt').value = text;
            sendMessage();
        }

        // 清空响应
        function clearResponse() {
            document.getElementById('responseArea').style.display = 'none';
            document.getElementById('response').textContent = '';
            document.getElementById('status').style.display = 'none';
        }

        // 显示状态信息
        function showStatus(message, type) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = `status ${type}`;
            status.style.display = 'block';
        }
    </script>
</body>
</html> 